package io.acm.modules.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.acm.common.utils.R;
import io.acm.modules.app.dao.StuFileDao;

import io.acm.modules.app.entity.StuFileEntity;

import io.acm.modules.app.service.StuFileService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
import java.util.List;
import java.util.Map;

@Service("stufileService")
public class StuFileServiceImpl extends ServiceImpl<StuFileDao, StuFileEntity> implements StuFileService {

@Autowired
StuFileService stuFileService;

    @Override
    public R searchById(String id,String token) {

        LambdaQueryWrapper<StuFileEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StuFileEntity::getSId,id);
        int count = stuFileService.count(wrapper);
        if(count==1){
            StuFileEntity student = stuFileService.getById(id);
            return R.ok().put("result", student);
        }

        String url = "http://10.10.31.200:8863/open_api/customization/vbzksinfo/full";
        URL urlObject = null;
        try {
            urlObject = new URL(url + "?access_token=" + token + "&XH=" + id);
            HttpURLConnection connection = (HttpURLConnection) urlObject.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setDoOutput(true);
            int responseCode = connection.getResponseCode();
            System.out.println(responseCode);
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 读取响应
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();

                // 解析JSON响应
                ObjectMapper objectMapper = new ObjectMapper();
                objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
                String jsonResponse = response.toString();
                Map<String, Object> apiResponse = objectMapper.readValue(jsonResponse, Map.class);

                // 获取result字段
                Map<String, Object> result = (Map<String, Object>) apiResponse.get("result");

                // 获取data数组中的第一个元素
                List<Map<String, String>> dataList = (List<Map<String, String>>) result.get("data");
                Map<String, String> studentData = dataList.get(0);

                System.out.println(studentData);
                // 替换XBMC字段的值
                String gender = studentData.get("XBMC");
                if ("男".equals(gender)) {
                    studentData.put("XBMC", "1");
                } else if ("女".equals(gender)) {
                    studentData.put("XBMC", "0");
                } else {
                    // 处理其他情况，比如未知性别
                }
                // 创建Student实体对象
                StuFileEntity student = new StuFileEntity();
                student.setSId(studentData.get("XH"));
                student.setUserName(studentData.get("XM"));
                student.setCollege(studentData.get("DWMC"));
                student.setMajor(studentData.get("ZYMC"));
                student.setClassName(studentData.get("BJMC"));
                student.setSex(Integer.parseInt(studentData.get("XBMC")));
                //StuFileEntity student = objectMapper.convertValue(studentData, StuFileEntity.class);

                return R.ok().put("result", student);

            } else {
                System.out.println("HTTP Request failed with status code: " + responseCode);
            }

            // 关闭连接
            connection.disconnect();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return R.ok().put("result", "");

    }

    @Override
    public String findToken() {
        String url = "http://10.10.31.200:8863/open_api/authentication/get_access_token?key=201911223234111914&secret=ba2d20fe67fd3cc2ab04ec1c52f5ab224e618066";
        URL urlObject = null;
        try {
            urlObject = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) urlObject.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setDoOutput(true);
            int responseCode = connection.getResponseCode();
            System.out.println(responseCode);
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 读取响应
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();

                // 解析JSON响应
                ObjectMapper objectMapper = new ObjectMapper();

                String jsonResponse = response.toString();
                Map<String, Object> apiResponse = objectMapper.readValue(jsonResponse, Map.class);
                System.out.println(jsonResponse);
                Map<String, Object> result = (Map<String, Object>) apiResponse.get("result");

                // 从result中获取"access_token"
                String accessToken = (String) result.get("access_token");
                return  accessToken;
            }
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        } catch (ProtocolException e) {
            throw new RuntimeException(e);
        } catch (JsonMappingException e) {
            throw new RuntimeException(e);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return null;
    }
}
